package com.wtao.imagereader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.wtao.imagereader.utils.AutoFitTextureView;
import com.wtao.imagereader.utils.FileUtils;
import com.wtao.imagereader.utils.TimeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Camera2MutilPreviewActivity extends BaseActivity implements View.OnClickListener {
    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
    private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();

    private static final String TAG = "Camera2Activity";

    static {
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    static {
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
    }

    private AutoFitTextureView mTextureView;
    private TextView timeTv;
    private Button mButtonVideo;

    private CameraDevice mCameraDevice;
    private int cameraId;
    private int previewWidth, previewHeight;
    private int cameraIds[] = {45,2};
    private Size[] allSize = {new Size(1920,1080),new Size(1920,1080)};
    private CameraCaptureSession mPreviewSession;
    public static int MSG_ID_UPDATE_TIME = 99;
    private int recordTime;//录制了多少秒
    private Size mPreviewSize;
    private Size mVideoSize;
     private boolean mIsRecordingVideo;

    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;
    private ImageReader mImageReader;

    private Semaphore mCameraOpenCloseLock = new Semaphore(1);
    private EditText etSaveName;
    private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            Log.e(TAG, "onOpened");
            mCameraDevice = cameraDevice;

            mCameraOpenCloseLock.release();
            if (null != mTextureView) {
                configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
            }
            startPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            Log.e(TAG, "onDisconnected");
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            Log.e(TAG, "onError error="+error);

            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            finish();
        }

    };
    private CaptureRequest.Builder mPreviewBuilder;

    //更新显示录制的时间
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_ID_UPDATE_TIME) {
                recordTime++;
                updateTime();
                handler.sendEmptyMessageDelayed(MSG_ID_UPDATE_TIME, 1000);
            }
        }
    };

    public void updateTime() {
        String time = TimeUtil.sumSecondToTime(recordTime);
        timeTv.setText(time);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "---onCreate");
        setContentView(R.layout.activity_camera2_video_mutil);
        if (getIntent() != null) {
            String cameraIdStr = getIntent().getStringExtra("dmsCameraID");
            if (TextUtils.isEmpty(cameraIdStr)) {
                cameraIdStr = "1";
            }
            Log.e(TAG, "getIntent() != null cameraIdStr="+cameraIdStr);
            cameraId = Integer.parseInt(cameraIdStr);
            previewWidth = Integer.parseInt(getIntent().getStringExtra("width" ));
            previewHeight =Integer.parseInt( getIntent().getStringExtra("height" ));
        } else {
            cameraId = 0;
            previewWidth = 1920;
            previewHeight = 1080;
        }
        timeTv = findViewById(R.id.tvTime);
        mTextureView = (AutoFitTextureView) findViewById(R.id.texture);
        mButtonVideo = (Button) findViewById(R.id.video);
        mButtonVideo.setOnClickListener(this);

        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                //可以使用surface,在这里打开摄像头
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                //纹理尺寸变化

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {

                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {


            }
        });

        etSaveName = findViewById(R.id.saveName);
        findViewById(R.id.switchCamera).setOnClickListener(this);
    }

    @Override
    protected void initView() {

    }

    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();
        //不要在onResume里openCamera，而是在textureView的onSurfaceTextureAvailable打开摄像头，不然重新进入录屏界面会报错说session关闭了
        /*if (mTextureView.isAvailable()) {
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            Log.e(TAG, "onResume()->isAvailable()false 直接设置的回调监听");
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }*/
    }

    @Override
    public void onPause() {
        Log.e(TAG, "onPause");

        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop()");
        closeCamera();
        if (mBackgroundThread != null) {
            stopBackgroundThread();
        }
        handler.removeMessages(MSG_ID_UPDATE_TIME);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back: {
                Log.e(TAG, "bt_back click");
                closeCamera();
                if (mBackgroundThread != null) {
                    stopBackgroundThread();
                }
                finish();
            }
            break;
            case R.id.video: {

                break;
            }
            case R.id.switchCamera: {
                Log.e(TAG, "");
                closeCamera();
                closePreviewSession();
                int index = 0;
                for(int i=0;i<cameraIds.length;i++){
                    if(cameraId==cameraIds[i]){
                        index=i;
                        break;
                    }
                }
                int newIndex = (index+1)%cameraIds.length;
                Log.e(TAG, "当前下标i="+index+" 新的原始下标："+newIndex);
                cameraId = cameraIds[newIndex];
                Size currentSize = allSize[newIndex];
                openCamera(currentSize.getWidth(),currentSize.getHeight());
                break;
            }
        }
    }

    /**
     * Starts a background thread and its {@link Handler}.
     */
    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    /**
     * Stops the background thread and its {@link Handler}.
     */
    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
     */
    @SuppressWarnings("MissingPermission")
    private void openCamera(int width, int height) {
        Log.e(TAG, "openCamera: " + width + "---" + height+" cameraId="+cameraId);
        setUpCameraOutputs(width, height);
        configureTransform(width, height);

        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            Log.d(TAG, "tryAcquire");
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(String.valueOf(cameraId));
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
             Size[] sizes = map.getOutputSizes(ImageFormat.JPEG);
            for (int i = 0; i < sizes.length; i++) { //遍历所有Size
                Size itemSize = sizes[i];
                Log.e(TAG, "itemSize 宽=" + itemSize.getWidth() + "高=" + itemSize.getHeight());
            }
            if (map == null) {
                throw new RuntimeException("Cannot get available preview/video sizes");
            }
            if (previewHeight > 0 && previewWidth > 0) {
                mVideoSize = new Size(previewWidth, previewHeight);
                mPreviewSize = new Size(previewWidth, previewHeight);
            } else {
                mVideoSize = new Size(1920, 1080);
                mPreviewSize = new Size(1920, 1080);
            }
            Log.e(TAG, "  mPreviewSize.getWidth()=" + mPreviewSize.getWidth() + "  getHeight()=" + mPreviewSize.getHeight());

            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            } else {
                mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }
            Log.e(TAG, "configureTransform->传递参数："+mPreviewSize.getWidth()+" "+ mPreviewSize.getHeight());
            configureTransform(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            manager.openCamera(String.valueOf(cameraId), mStateCallback, null);
        } catch (CameraAccessException e) {
            Log.e(TAG, "Cannot access the camera");
            Toast.makeText(this, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
            finish();
        } catch (NullPointerException e) {
            e.printStackTrace();
            Toast.makeText(this, getString(R.string.camera_error), Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.");
        }
    }

    /**
     * Sets up member variables related to camera.
     *
     * @param width  The width of available size for camera preview
     * @param height The height of available size for camera preview
     */
    @SuppressWarnings("SuspiciousNameCombination")
    private void setUpCameraOutputs(int width, int height) {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }

                StreamConfigurationMap map = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }

                mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.YUV_420_888,2);
                mImageReader.setOnImageAvailableListener( mOnImageAvailableListener, mBackgroundHandler);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            final Image image = reader.acquireLatestImage();   // 获取最近一帧图像
            mBackgroundHandler.post(new Runnable() {    // 在子线程执行，防止预览界面卡顿
                @Override
                public void run() {

                    image.close();//这里需要关闭，不然会卡死预览界面
                }
            });
        }
    };

    private void onPictureTaken(byte[] imageBuffer, int frame) {
        ByteBuffer mTmpBuffer = ByteBuffer.allocate(previewWidth * previewHeight * 4);
        mTmpBuffer.put(imageBuffer);

        File file = FileUtils.getOutputMediaFile(this, frame);
        yuv2Picture(imageBuffer, previewWidth, previewHeight, file);
    }

    public static void yuv2Picture(byte[] data, int width, int height, File targetFile) {
        FileOutputStream stream = null;
        try {
            android.graphics.YuvImage image = new android.graphics.YuvImage(data, ImageFormat.NV21, width, height, null);
            stream = new FileOutputStream(targetFile);
            if (image.compressToJpeg(new Rect(0, 0, width, height), 100, stream)) {
                stream.flush();
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString(), e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            closePreviewSession();
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
            }

        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera closing.");
        } finally {
            mCameraOpenCloseLock.release();
        }
    }

    /**
     * Start the camera preview.
     */
    private void startPreview() {
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            //Log.e(TAG, "startPreview()-->下面有closePreviewSession()");
            //closePreviewSession();//这里注释了！！！不然会出现updatePreview(Camera2Activity.java:743)里报错IllegalStateException: Session has been closed; further changes are illegal.
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

            Surface previewSurface = new Surface(texture);
            mPreviewBuilder.addTarget(previewSurface);

            mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            mPreviewSession = session;
                            Log.e(TAG, "startPreview()-->mCameraDevice.createCaptureSession-->onConfigured");

                            updatePreview(mPreviewSession);
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            Toast.makeText(Camera2MutilPreviewActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onClosed(@NonNull CameraCaptureSession session) {
                            super.onClosed(session);
                            Log.e(TAG, "startPreview()-->mCameraDevice.createCaptureSession-->onClosed");
                        }
                    }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void updatePreview(CameraCaptureSession session) {
        if (null == mCameraDevice) {
            return;
        }
        try {
            setUpCaptureRequestBuilder(mPreviewBuilder);
            session.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
        builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    }

    private CaptureRequest.Builder mPreviewRequestBuilder;

    private CameraCaptureSession mCaptureSession;

    private CaptureRequest mPreviewRequest;

    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            // We configure the size of default buffer to be the size of camera preview we want.
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // This is the output Surface we need to start preview.
            Surface surface = new Surface(texture);

            // We set up a CaptureRequest.Builder with the output Surface.
            mPreviewRequestBuilder
                    = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
            mPreviewRequestBuilder.addTarget(surface);


            // Here, we create a CameraCaptureSession for camera preview.
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // The camera is already closed
                            if (null == mCameraDevice) {
                                return;
                            }

                            // When the session is ready, we start displaying the preview.
                            mCaptureSession = cameraCaptureSession;
                            try {
                                // Auto focus should be continuous for camera preview.
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                                // Flash is automatically enabled when necessary.
//                                setAutoFlash(mPreviewRequestBuilder);

                                // Finally, we start displaying the camera preview.
                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                        null, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {

                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void configureTransform(int viewWidth, int viewHeight) {
        if (null == mTextureView || null == mPreviewSize) {
            return;
        }
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }


    private String getVideoFilePath(Context context) {
        final File dir = context.getExternalFilesDir(null);
        String saveName = etSaveName.getText().toString().trim();
        if (TextUtils.isEmpty(saveName)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
            File file1 = new File(dir.getAbsolutePath() + File.separator + "video_" + format.format(new Date()) + ".mp4");
            return file1.getAbsolutePath();
        } else {
            if (saveName.contains("\\.")) {
                File file1 = new File(dir.getAbsolutePath() + File.separator + saveName);
                if (file1.exists()) {
                    file1.delete();
                }
                return file1.getAbsolutePath();

            } else { //不带文件后缀
                File file1 = new File(dir.getAbsolutePath() + File.separator + saveName + ".mp4");
                if (file1.exists()) {
                    file1.delete();
                }
                return file1.getAbsolutePath();
            }
        }
    }


    private void closePreviewSession() {
        if (mPreviewSession != null) {
            Log.e(TAG, "closePreviewSession()");
            mPreviewSession.close();
            mPreviewSession = null;
        }
    }



    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            // We cast here to ensure the multiplications won't overflow
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }

    }

    public static class ErrorDialog extends DialogFragment {

        private static final String ARG_MESSAGE = "message";

        public static ErrorDialog newInstance(String message) {
            ErrorDialog dialog = new ErrorDialog();
            Bundle args = new Bundle();
            args.putString(ARG_MESSAGE, message);
            dialog.setArguments(args);
            return dialog;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Activity activity = getActivity();
            return new AlertDialog.Builder(activity)
                    .setMessage(getArguments().getString(ARG_MESSAGE))
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            activity.finish();
                        }
                    })
                    .create();
        }

    }


}
